import { logger } from '../utils/logger';
import prisma from '../lib/prisma';
import axios from 'axios';
import { QuestionType, Difficulty } from '@prisma/client';

interface GenerationCriteria {
  subject: string;
  topic: string;
  difficulty: Difficulty;
  type: QuestionType;
  count: number;
  keywords?: string[];
  excludeIds?: string[];
}

interface GeneratedQuestion {
  title: string;
  content: string;
  type: QuestionType;
  difficulty: Difficulty;
  choices?: string[];
  correctAnswer: string;
  explanation: string;
  knowledgePoints: string[];
  tags: string[];
}

export class AIQuestionGenerationService {
  private static readonly API_ENDPOINT = process.env.AI_QUESTION_GEN_API_URL;
  private static readonly API_KEY = process.env.AI_QUESTION_GEN_API_KEY;

  // 生成题目
  static async generateQuestions(criteria: GenerationCriteria): Promise<GeneratedQuestion[]> {
    try {
      // 调用AI服务生成题目
      const response = await axios.post<GeneratedQuestion[]>(
        this.API_ENDPOINT as string,
        criteria,
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const generatedQuestions = response.data;

      // 将生成的题目保存到数据库
      const savedQuestions = await Promise.all(
        generatedQuestions.map(async (question) => {
          const saved = await prisma.question.create({
            data: {
              title: question.title,
              content: question.content,
              type: question.type,
              difficulty: question.difficulty,
              choices: question.choices || [],
              correctAnswer: question.correctAnswer,
              explanation: question.explanation,
              knowledgePoints: question.knowledgePoints,
              tags: question.tags,
              aiGenerated: true,
              metadata: {
                generationCriteria: criteria,
                generatedAt: new Date().toISOString()
              }
            }
          });
          return saved;
        })
      );

      logger.info('AI生成题目成功', {
        count: savedQuestions.length,
        criteria
      });

      return savedQuestions;
    } catch (error) {
      logger.error('AI生成题目失败', { error, criteria });
      throw new Error('AI生成题目失败，请稍后再试');
    }
  }

  // 根据已有题目生成相似题目
  static async generateSimilarQuestions(
    questionId: string,
    count: number
  ): Promise<GeneratedQuestion[]> {
    try {
      // 获取原题目信息
      const originalQuestion = await prisma.question.findUnique({
        where: { id: questionId }
      });

      if (!originalQuestion) {
        throw new Error('原题目不存在');
      }

      // 调用AI服务生成相似题目
      const response = await axios.post<GeneratedQuestion[]>(
        `${this.API_ENDPOINT}/similar` as string,
        {
          originalQuestion,
          count
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const generatedQuestions = response.data;

      // 保存生成的题目
      const savedQuestions = await Promise.all(
        generatedQuestions.map(async (question) => {
          const saved = await prisma.question.create({
            data: {
              title: question.title,
              content: question.content,
              type: question.type,
              difficulty: question.difficulty,
              choices: question.choices || [],
              correctAnswer: question.correctAnswer,
              explanation: question.explanation,
              knowledgePoints: question.knowledgePoints,
              tags: question.tags,
              aiGenerated: true,
              metadata: {
                originalQuestionId: questionId,
                generatedAt: new Date().toISOString()
              }
            }
          });
          return saved;
        })
      );

      logger.info('AI生成相似题目成功', {
        originalQuestionId: questionId,
        count: savedQuestions.length
      });

      return savedQuestions;
    } catch (error) {
      logger.error('AI生成相似题目失败', { error, questionId, count });
      throw new Error('AI生成相似题目失败，请稍后再试');
    }
  }

  // 根据知识点生成题目
  static async generateByKnowledgePoints(
    knowledgePoints: string[],
    criteria: Omit<GenerationCriteria, 'topic'>
  ): Promise<GeneratedQuestion[]> {
    try {
      // 调用AI服务生成题目
      const response = await axios.post<GeneratedQuestion[]>(
        `${this.API_ENDPOINT}/knowledge-points` as string,
        {
          knowledgePoints,
          ...criteria
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const generatedQuestions = response.data;

      // 保存生成的题目
      const savedQuestions = await Promise.all(
        generatedQuestions.map(async (question) => {
          const saved = await prisma.question.create({
            data: {
              title: question.title,
              content: question.content,
              type: question.type,
              difficulty: question.difficulty,
              choices: question.choices || [],
              correctAnswer: question.correctAnswer,
              explanation: question.explanation,
              knowledgePoints: question.knowledgePoints,
              tags: question.tags,
              aiGenerated: true,
              metadata: {
                targetKnowledgePoints: knowledgePoints,
                generationCriteria: criteria,
                generatedAt: new Date().toISOString()
              }
            }
          });
          return saved;
        })
      );

      logger.info('AI根据知识点生成题目成功', {
        knowledgePoints,
        count: savedQuestions.length
      });

      return savedQuestions;
    } catch (error) {
      logger.error('AI根据知识点生成题目失败', {
        error,
        knowledgePoints,
        criteria
      });
      throw new Error('AI生成题目失败，请稍后再试');
    }
  }
}
